#include "stdafx.h"
#include "CRC.h"

static int crcTable[256];
static bool crcTableValid;

static void calculateCRCTable()
{
	int val;

	for(int i = 0; i < 256; i++)
	{
		val = i;
		for(int j = 0; j < 8; j++)
		{
			if(val & 0x01)
				val = 0xedb88320 ^ (val >> 1);
			else
				val = val >> 1;
		}
		crcTable[i] = val;
	}

	crcTableValid = true;
}



int CRC::calculateCRC(const void * buffer, int len, int crcVal )
{
	// check if need to generate the crc table
	if(!crcTableValid)
		calculateCRCTable();

	// now calculate the crc
	char * buf = (char*)buffer;
	for(int i = 0; i < len; i++)
		crcVal = crcTable[(crcVal ^ buf[i]) & 0xff] ^ (crcVal >> 8);
	return(crcVal);
}
